<template>
  <div class="headline">
    <a-tree-select
      v-model:value="queryParas"
      style="width: 25%"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
      :tree-data="treeData"
      placeholder="请选择上级"
      tree-default-expand-all
      @select="onSelect"
    >
    </a-tree-select>
    <a-button class="user-btn" type="primary" @click="onQuery"> 查询 </a-button>
    <a-button class="user-btn" type="primary" @click="onAdd"> 添加 </a-button>
  </div>
  <a-table
    :columns="columns"
    :row-key="(record) => record.id"
    :data-source="data"
    :loading="loading"
    @change="handleTableChange"
  >
    <template #action="{ record }">
      <span>
        <a-button class="user-btn" type="primary" @click="onSave(record)">
          修改
        </a-button>
        <a-button class="user-btn" type="danger" @click="onDelete(record)">
          删除
        </a-button>
      </span>
    </template>
  </a-table>
  <a-drawer
    :title="drawerTitle"
    placement="right"
    :visible="visible"
    @close="onClose"
    width="500"
  >
    <a-form
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      style="margin-top: 20px"
    >
      <a-form-item label="上级分类" name="higherId">
        <a-tree-select
          v-model:value="form.categoryId"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="treeData"
          placeholder="请选择上级"
          tree-default-expand-all
          @select="onHigherIdSelect"
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item label="分类名称" name="name">
        <a-input type="text" v-model:value="form.name" autocomplete="off" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" />
      </a-form-item>
      <a-form-item label="排序号" name="sequence">
        <a-input
          type="number"
          v-model:value="form.sequence"
          autocomplete="off"
        />
      </a-form-item>
      <a-form-item>
        <a-checkbox @change="onChange" v-model:checked="form.enabled">
          启用
        </a-checkbox>
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button class="user-btn" type="primary" @click="onSubmit">
          保存
        </a-button>
        <a-button class="user-btn" @click="resetForm" v-if="!addFlag">
          重置
        </a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>
<script>
import {
  sysCategoryAllAPI,
  sysDataByCateIdAPI,
  sysDataAddAPI,
  sysDataDeleteAPI,
  sysDataModyfyByIdAPI,
} from "../../api/api";
import { message } from "ant-design-vue";
import { stringify } from "querystring";
import { Modal } from "ant-design-vue";
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    width: "10%",
  },
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    width: "10%",
  },
  {
    title: "备注",
    dataIndex: "remark",
    width: "15%",
  },

  {
    title: "排序号",
    dataIndex: "sequence",
    width: "10%",
  },
  {
    title: "父级名称",
    dataIndex: "categoryName",
    width: "15%",
  },
  {
    title: "启用状态",
    dataIndex: "enabled",
    width: "10%",
  },
  {
    title: "操作",
    key: "action",
    slots: { customRender: "action" },
  },
];

export default {
  data() {
    return {
      treeData: [],
      queryParas: 0,
      data: [],
      loading: false,
      columns,
      reloadFlag: false, //重新加载列表数据
      addFlag: true, //添加操作
      //drawer
      visible: false,
      confirmLoading: false,
      drawerTitle: "",
      //drawer form
      labelCol: { span: 4 },
      wrapperCol: { span: 12 },

      form: {
        id: null,
        name: "",
        remark: "",
        sequence: "",
        enabled: true,
        categoryId: 0,
        categoryName: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
        remark: [
          {
            required: true,
            message: "请输入备注",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.fetch();
    this.fetchCategorys();
  },
  methods: {
    onQuery() {
      this.fetch(this.queryParas);
    },
    handleTableChange(pagination, filters, sorter) {
      this.fetch(this.queryParas);
    },
    onSelect(value, node, extra) {
      this.queryParas = value;
      this.fetch(value);
    },
    fetchCategorys(params) {
      sysCategoryAllAPI(params).then((res) => {
        if (res.data.succeeded) {
          var rootNode = {};
          (rootNode.id = 0), (rootNode.name = "根节点");
          rootNode.remark = "根节点";
          rootNode.higherId = -1;
          rootNode.sequence = 1;
          rootNode.enabled = true;
          res.data.data.push(rootNode);
          this.treeData = this.convertToTreeData(res.data.data, -1);
        } else {
          message.error(res.data.errors);
        }
      });
    },
    fetch(params = {}) {
      this.loading = true;
      sysDataByCateIdAPI(params).then((res) => {
        this.loading = false;
        this.data = res.data.data;
      });
    },
    convertToTreeData(data, higherId) {
      const result = [];
      let temp = [];
      for (let i = 0; i < data.length; i++) {
        data[i].higherId = data[i].higherId == null ? 0 : data[i].higherId;
        if (data[i].higherId === higherId) {
          const key = data[i].id;
          let item = {};
          item.key = data[i].id;
          item.value = data[i].id;
          item.title = data[i].name;
          item.isLeaf = true;
          temp = this.convertToTreeData(data, data[i].id);
          if (temp.length > 0) {
            item.isLeaf = false;
            item.children = temp;
          }
          result.push(item);
        }
      }
      return result;
    },
    onAdd() {
      this.drawerTitle = "添加字典";
      this.addFlag = true;
      this.form.categoryId=this.queryParas
      this.showDrawer();
    },
    //Drawer
    showDrawer() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
      this.form.name = "";
      this.form.id = 0;
      this.form.remark = "";
      this.form.sequence = 0;
      this.form.enabled = false;
      this.form.categoryId = 0;
      this.form.categoryName = "";
      if (this.reloadFlag) {
        this.reloadFlag = false;
        this.onQuery();
      }
    },
    onSave(record) {
      this.form.id = record.id;
      this.form.name = record.name;
      this.form.remark = record.remark;
      this.form.sequence = record.sequence;
      this.form.enabled = record.enabled;
      this.form.categoryId = record.categoryId;
      this.form.categoryName = record.categoryName;
      this.drawerTitle = "修改字典";
      this.addFlag = false;
      this.showDrawer();
    },
    onDelete(record) {
      let _this = this;
      var params = "";
      Modal.confirm({
        title: "您确认删除吗?",
        content: "数据删除后将无法恢复",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          params += "?dataids=" + record.id;
          sysDataDeleteAPI(record.categoryId, params).then((res) => {
            if (res.data.succeeded) {
              message.success("删除成功！");
              _this.onQuery();
            } else {
              message.error(res.data.errors);
            }
          });
        },
        onCancel() {},
      });
    },
    //Drawer form
    onSubmit() {
      this.$refs.ruleForm
        .validate()
        .then(() => {
          var model = JSON.parse(JSON.stringify(this.form));
          var categoryid = model.categoryId;
          var dataid = model.id;
          Reflect.deleteProperty(model, "id");
          Reflect.deleteProperty(model, "categoryId");
          Reflect.deleteProperty(model, "categoryName");
          if (this.addFlag) {
            //添加
            sysDataAddAPI(categoryid, model).then((res) => {
              if (res.data.succeeded) {
                this.reloadFlag = true;
                message.success("保存成功！");
              } else {
                message.error(res.data.errors);
              }
            });
          } else {
            //修改
            sysDataModyfyByIdAPI(categoryid, dataid, model).then((res) => {
              if (res.data.succeeded) {
                this.reloadFlag = true;
                message.success("保存成功！");
              } else {
                message.error(res.data.errors);
              }
            });
          }
        })
        .catch((error) => {
          console.log("error", error);
        });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>
<style lang="scss">
.headline {
  height: 50px;
  padding: 10px;
  display: flex;
  align-items: center;
}
.headline input {
  width: 200px;
  margin-right: 10px;
}
.headline button {
  margin-right: 10px;
}
.user-btn {
  margin: 5px;
}
</style>